package org.scc.dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.scc.util.MybatisUtil;

/**
 * dao层基类
 * 封装了mybatis常用的数据库操作
 * @author rzpeng
 *
 */
public abstract class BaseDao {
	private static Logger log = Logger.getLogger(BaseDao.class);
	
	/**
	 * 取得调用mybatis方法的mapper名称
	 * 前半部分是sqlmapper的namespace，后半部分是对应的id，点号连接
	 * @param methodName
	 * @return
	 */
	protected abstract String getMapper(String methodName);
	
	protected <T> T selectOne(String mapper, Object param, String logInfo){
		SqlSession session = MybatisUtil.openSession();
		try {
			return session.selectOne(mapper, param);
		} catch (Exception e) {
			log.error(logInfo, e);
			return null;
		} finally {
			session.close();
		}
	}
	
	protected <T> T selectOne(String mapper, String logInfo){
		SqlSession session = MybatisUtil.openSession();
		try {
			return session.selectOne(mapper);
		} catch (Exception e) {
			log.error(logInfo, e);
			return null;
		} finally {
			session.close();
		}
	}
	
	protected <T> List<T> selectList(String mapper, Object param, String logInfo){
		SqlSession session = MybatisUtil.openSession();
		try {
			return session.selectList(mapper, param);
		} catch (Exception e) {
			log.error(logInfo, e);
			return null;
		} finally {
			session.close();
		}
	}
	
	protected <T> List<T> selectList(String mapper, String logInfo){
		SqlSession session = MybatisUtil.openSession();
		try {
			return session.selectList(mapper);
		} catch (Exception e) {
			log.error(logInfo, e);
			return null;
		} finally {
			session.close();
		}
	}
	
	protected void insert(String mapper, Object obj, String logInfo){
		SqlSession session = MybatisUtil.openSession();
		try {
			session.insert(mapper, obj);
			session.commit();
		} catch (Exception e) {
			session.rollback();
			log.error(logInfo, e);
		} finally {
			session.close();
		}
	}
	
	protected void delete(String mapper,Object obj, String logInfo){
		SqlSession session = MybatisUtil.openSession();
		try {
			session.delete(mapper, obj);
			session.commit();
		} catch (Exception e) {
			session.rollback();
			log.error(logInfo, e);
		} finally {
			session.close();
		}
	}
	
	protected void update(String mapper, Object obj, String logInfo){
		SqlSession session = MybatisUtil.openSession();
		try {
			session.update(mapper, obj);
			session.commit();
		} catch (Exception e) {
			session.rollback();
			log.error(logInfo, e);
		} finally {
			session.close();
		}
	}
	
}
